package tool.codescan.mappers;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import tool.data.TypeDefinition;


	/**
	 * @author Jamie
	 * @date 2013/11/14
	 * 
	 * This class is responsible for resolving package addresses for types.
	 * 
	 *  This is necessary as some projects use 'package.*;' imports which include arbitrarily large
	 *  name-spaces in a class's imports.  Star imports are normally resolved at compile time to
	 *  explicit imports which is possible because Types may not have an ambiguous definition in
	 *  the import list.
	 *  
	 */

public class PackageMapper {

	File rootDirectory;
	PackageNode rootNode;
	
	public PackageMapper (File location) {
		
		rootDirectory = location;
		
		doMapping();
	}
	
	
	/*
	 * Maps the directory structure from the root directory, assumptions:
	 * - The file structure mirrors the package structure
	 * - We are only looking for .java files
	 * - Each .java file is named the same as the contained type.
	 * 
	 */
	private final void doMapping () {
	
	    // Only final methods should be called from a constructor
		// Create a root node - the tree with build itself recursively.
		rootNode = new PackageNode(rootDirectory, null);
		
	}
	
	
	/**
	 * Resolves a Type name to a full 'package*.type' form if the information is available to do so
	 * @param typeName - the object representing the name of the type to resolve
	 * @param partialImport - the star import that may contain the Type requested of the form
	 * 					   'package.package'
     * @return - TypeDefinition - updated object representing the name of the parameter if any 
     *           relevant path information is found.
	 */
	public TypeDefinition resolvePackageForType (TypeDefinition name, String partialImport) {
		
		String [] packages = partialImport.split(Pattern.quote("."));
		List<String> packageList = new ArrayList<>();
				
		for (String s : packages) {
			
			packageList.add(s);
			
		}
		
		TypeDefinition reply = rootNode.getPathForType(name, packageList);
		
		return reply;
		
	}
	
	
	@Override
	public String toString () {
		
		String reply = "\nListing of Package Map:\n";
		
		reply += rootNode.toString();
		
		return reply;
		
	}
	
}
